package com.mezz.bones.framework.sse.boot;

import com.mezz.bones.framework.base.util.IdUtil;
import com.mezz.bones.framework.sse.service.SseSessionManager;
import jakarta.servlet.http.HttpServletResponse;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.util.UUID;

@RestController
@RequestMapping("/sse")
@AllArgsConstructor
@Slf4j
public class SseController {

    private final SseSessionManager sseSessionManager;

    @GetMapping("/connect")
    public SseEmitter connect(@RequestParam String userId, HttpServletResponse response) {
        response.setHeader("Cache-Control", "no-cache");
        response.setHeader("X-Accel-Buffering", "no");
        response.setContentType(MediaType.TEXT_EVENT_STREAM_VALUE);

        SseEmitter emitter = new SseEmitter(0L);
        String clientId = userId + "_" + IdUtil.nextId("sse_client");

        // 添加连接日志
        int currentConnections = sseSessionManager.getClientCount(userId);
        log.info("[SSE Connect] 新连接建立 - userId={}, clientId={}, 当前用户连接数={}, 总连接数={}",
            userId, clientId, currentConnections + 1, sseSessionManager.getTotalConnections());
        
        sseSessionManager.addSession(userId, clientId, emitter);
        
        emitter.onCompletion(() -> {
            sseSessionManager.removeSession(userId, clientId);
            // 添加关闭日志
            log.info("[SSE Complete] 连接正常关闭 - userId={}, clientId={}, 剩余该用户连接数={}, 总连接数={}",
                userId, clientId, sseSessionManager.getClientCount(userId), sseSessionManager.getTotalConnections());
        });
        
        emitter.onTimeout(() -> {
            sseSessionManager.removeSession(userId, clientId);
            // 添加超时日志
            log.warn("[SSE Timeout] 连接超时关闭 - userId={}, clientId={}, 剩余该用户连接数={}, 总连接数={}",
                userId, clientId, sseSessionManager.getClientCount(userId), sseSessionManager.getTotalConnections());
        });
        
        emitter.onError((ex) -> {
            sseSessionManager.removeSession(userId, clientId);
            // 添加错误日志
            log.error("[SSE Error] 连接异常关闭 - userId={}, clientId={}, 剩余该用户连接数={}, 总连接数={}, 错误信息={}",
                userId, clientId, sseSessionManager.getClientCount(userId), sseSessionManager.getTotalConnections(), ex.getMessage(), ex);
        });
        
        return emitter;
    }
}